//
//  CellForHistory.m
//  世界
//
//  Created by dllo on 16/3/2.
//  Copyright © 2016年 admin. All rights reserved.
//

#import "CellForHistory.h"
#import "ModelForFocusNews.h"
#import <MJRefresh.h>
#import <UIImageView+WebCache.h>
#import "CellForFocusNewsList.h"
#import "CellForFocusNewsListNoPhoto.h"
#import "ViewControllerForNewsDetails.h"

@interface CellForHistory ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UITableView *tabView;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, retain) NSMutableArray *arrModelForList;
@property (nonatomic, retain) NSMutableArray *arrForPicUrl;

@end


@implementation CellForHistory


#pragma mark 重写初始化方法
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self != nil)
    {
        //创建子控件
        self.arrModelForList = [NSMutableArray array];
        
        self.arrForPicUrl = [NSMutableArray array];
        
        self.page = 1;
        
        [self createTabView];
        
        [self handleData];
        
        
        self.tabView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            
            self.page = 1;
            
            [self.arrModelForList removeAllObjects];
            
            [self.arrForPicUrl removeAllObjects];
            
            [self handleData];
            
        }];

        
        
    }
    return self;
}




#pragma mark 子控件的布局
- (void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes
{
    //collectionCell 的子控件的布局通常在此方法中设置
    [super applyLayoutAttributes:layoutAttributes];
    
    //设置tabView的空间位置及大小
    self.tabView.frame = self.contentView.frame;
}



#pragma mark 自定义方法 >>>>>>
#pragma mark 处理数据
- (void)handleData
{
    NSURL *url = [NSURL URLWithString:@"http://admin.militaryapp.china.com/News/NewsServlet.do"];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    request.HTTPMethod = @"POST";
    
    NSString *body = [NSString stringWithFormat:@"page=%ld&pageSize=20&processID=getNewsList&type=4", self.page++];
    
    request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask *task =  [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        
        
        //解析
        NSError *errorOfJSON = nil;
        
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorOfJSON];
        
        
        NSArray *arr = [result objectForKey:@"data"];
        
        for (NSDictionary *dic in arr)
        {
            ModelForFocusNews *model = [[ModelForFocusNews alloc] init];
            
            [model setValuesForKeysWithDictionary:dic];
            
            [self.arrModelForList addObject:model];
            
            NSString *str = [dic objectForKey:@"PicUrl"];
            
            [self.arrForPicUrl addObject:str];
            
            [model release];
        }
        
        //回到主线程
        dispatch_sync(dispatch_get_main_queue(), ^{
            
            [self.tabView reloadData];
            
            self.tabView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
                
                // 进入刷新状态后会自动调用这个block
                if (self.page < 6)
                {
                    [self handleData];
                }
                else
                {
                    [self.tabView.mj_footer endRefreshing];
                }
            }];

            [self.tabView.mj_header endRefreshing];
            
            [self.tabView.mj_footer endRefreshing];
        });
    }];
    //开始任务
    [task resume];
}


#pragma mark 创建TabView
- (void)createTabView
{
    
    self.tabView = [[UITableView alloc] init];
    
    [self.contentView addSubview:self.tabView];
    
    
    [_tabView release];
    
    //指定代理人
    self.tabView.dataSource = self;
    self.tabView.delegate = self;
    
    //注册Cell
    [self.tabView registerClass:[CellForFocusNewsList class] forCellReuseIdentifier:@"pool1"];
    [self.tabView registerClass:[CellForFocusNewsListNoPhoto class] forCellReuseIdentifier:@"pool2"];
    
    //去掉分割线
    //self.tabView.separatorStyle = UITableViewCellSeparatorStyleNone;
}




#pragma mark UITableViewDataSource 协议方法
#pragma mark 相应分区的行的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrModelForList.count;
}




#pragma mark 给每行添加cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    if ([self.arrForPicUrl[indexPath.row] isEqualToString:@""])
    {
        
        CellForFocusNewsListNoPhoto *cell = [tableView dequeueReusableCellWithIdentifier:@"pool2"];
        
        //去掉选择cell之后背景颜色灰的效果
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        ModelForFocusNews *model1 = [self.arrModelForList objectAtIndex:indexPath.row];
        
        [cell handleData:model1];
        
        return cell;
    }
    else
    {
        CellForFocusNewsList *cell = [tableView dequeueReusableCellWithIdentifier:@"pool1"];
        
        
        //去掉选择cell之后背景颜色灰的效果
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        ModelForFocusNews *model = [self.arrModelForList objectAtIndex:indexPath.row];
        
        [cell handleData:model];
        
        return cell;
    }
}




#pragma mark UITableViewDelegate 协议方法
#pragma mark 设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}




#pragma mark 选择相应的行所触发的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    ViewControllerForNewsDetails *vc = [[ViewControllerForNewsDetails alloc] init];
    
    
    ModelForFocusNews *model2 = [self.arrModelForList objectAtIndex:indexPath.row];
    
    vc.strForNewsUrl = model2.NewsUrl;
    
    // 获取该视图层最下边的VC.
    id object = [self nextResponder];
    while (![object isKindOfClass:[UIViewController class]] &&
           object != nil) {
        object = [object nextResponder];
    }
    UIViewController *vc1 = (UIViewController*)object;
    
    
    
    
    //1.设置self.tabBarController.tabBar.hidden=YES;
    vc1.tabBarController.tabBar.hidden = YES;
    
    //2.如果在push跳转时需要隐藏tabBar，设置self.hidesBottomBarWhenPushed=YES;
    vc1.hidesBottomBarWhenPushed=YES;
    
    [vc1.navigationController pushViewController:vc animated:YES];
    
    
    //3.在push后设置self.hidesBottomBarWhenPushed=NO,这样back回来的时候，tabBar会恢复正常显示。
    vc1.hidesBottomBarWhenPushed=NO;
    
    //    [[NSNotificationCenter defaultCenter] postNotificationName:@"Video" object:nil userInfo:@{@"item" : self.arrMp4_url[indexPath.row - 1], @"title" : self.arrTitle[indexPath.row - 1], @"vid" : self.arrVid[indexPath.row - 1]}];
}


@end
